import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { previewDocByDocName, updatePreviewDocByMaterial } from '@/api/accept/business_Approve'
import { renderAsync } from 'docx-preview'
import moment from 'moment'
import { getSetting, getDecisionSetting } from '@/views/handleCase/base/formSetting'
import { Tp_procmaterialList } from '@/enumeration/Tp_procmaterial'
import { Tp_accept,Tp_hear,Tp_execute, Tp_proctypeEnum } from '@/enumeration/Tp_proctype'

export const BaseCaseHandleUpdateMinxin = {
  props: {
    applyid: {
      type: String,
      required: true
    },
    materialOption: {
      type: Object,
      required: true
    },
    busiType: {
      // 业务环节
      type: Number,
      required: true
    },
    decisionType: {
      // 决定类型
      type: Number,
      required: false
    },
  },
  data() {
    return {
      labelCol: { span: 4 }, // label宽
      wrapperCol: { span: 20 }, // 组件
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      loading: false, //按钮显示
      // modalVisible: false, // 模态框显示
      isResize: false,
      previewFileSrc: '',
      previewLoading: false,
      modalVisible: false,
      optionsData: {},

      formSetting: [], // 定义的表单配置
      modalTitle: '', // 标题名称
      // 动态表单数据
      infoForm: {},
      rules: {},
      currentFormSetting: {} // 当前的表单配置
    }
  },
  components: {
    Splitpanes,
    Pane
  },
  created() {
    this.infoForm.applyid = this.applyid
    this.formSetting = getSetting(this.busiType)
    // 决定阶段 特殊处理
    if (this.busiType == Tp_proctypeEnum.hear_decision.value) {
      this.formSetting = getDecisionSetting(this.decisionType)
    } 
  },
  methods: {
    init() {
      this.modalVisible = true
      this.initFormAndRule()
      this.$nextTick(() => {
        this.initOptionMaterial()
      })
    },
    // 初始化表单配置
    initFormAndRule() {
      this.infoForm = {} // 表单
      this.rules = {} // 规则
      // 构建当前的infoForm字段
      if (this.formSetting) {
        this.currentFormSetting = this.formSetting.filter(element => element.materialType == this.materialOption.mattype)[0]
      }
      if (this.currentFormSetting && this.currentFormSetting.formItem && this.currentFormSetting.formItem.length > 0) {
        for (let formItem of this.currentFormSetting.formItem) {
          this.$set(this.infoForm, formItem.key, formItem.default)
        }
        for (let rule in this.currentFormSetting.rules) {
          this.$set(this.rules, rule, this.currentFormSetting.rules[rule])
        }
        // this.$set(this.rules, this.currentFormSetting.rules)
        this.modalTitle = this.currentFormSetting.modalTitle
      } else {
        this.$message.error('当前查询表单配置错误')
        this.modalVisible = false
      }
    },
    /**
     * 初始化当前的数据
     */
    initOptionMaterial() {
      if (this.materialOption) {
        let docfield = JSON.parse(this.materialOption.docfiled)
        if (docfield) {
          for (let key in docfield) {
            this.$set(this.infoForm, key, docfield[key])
          }
        }
      }
      this.modalVisible = true
      this.previewDocByDocName()
    },

    previewDocByDocName() {
      let params = this.initDocParams()
      this.sendPreviewDocByDocName(params)
    },

    // 初始化对应的参数
    initDocParams() {
      let params = {
        applyid: this.applyid, // applyid
        materilaType: this.materialOption.mattype,
        docfield: null
      }
      let docfield = JSON.parse(JSON.stringify(this.infoForm))
      // 时间字段进行格式化
      if (this.currentFormSetting && this.currentFormSetting.formItem && this.currentFormSetting.formItem.length > 0) {
        for (let formItem of this.currentFormSetting.formItem) {
          if (formItem.type == 'date') {
            if (this.infoForm[formItem.key]) {
              let formateDate = this.$moment(this.infoForm[formItem.key]).format(formItem.format)
              docfield[formItem.key] = formateDate
            }
          }
        }
      }
      params.docfield = docfield
      console.log('入参参数：' + params)
      return params
    },

    /**
     * 提交表单
     */
    onSubmit() {
      this.$refs.formComponentRef.validate(valid => {
        this.loading = true
        if (valid) {
          console.log('submit!', this.infoForm)
          let params = this.initDocParams()
          this.sendSubmit(params, true)
        } else {
          this.focusRed()
        }
      })
    },

    handleCancel() {
      this.resetForm()
      this.$emit('reload')
      this.$emit('close')
      this.modalVisible = false
    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.formComponentRef.resetFields()
      })
    },

    /**
     * 换行替换
     */
    trimLine(str) {
      return str ? str.replace(/(\r\n|\n|\r)/gm, '').replace(/^\s*|\s*$/g, '') : ''
    },
    resize() {
      this.isResize = true
    },
    resized() {
      this.isResize = false
    },
    getUser() {
      return this.currentUser
    },
    /**
     * 调用接口
     * @param {} params
     */
    sendSubmit(params) {
      updatePreviewDocByMaterial(
        this.materialOption.id,
        this.currentUser.userId,
        this.currentUser.fullname,
        params.docfield
      ).then(res => {
        if (res.code !== 0) {
          this.$message.error('操作失败')
        } else {
          this.$message.success('操作成功')
          this.$emit('reload')
          this.$emit('close')
          this.modalVisible = false
        }
        this.loading = false
      })
    },

    /**
     * 表单focus标红部分
     * @returns
     */
    focusRed() {
      this.loading = false
      // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
      // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
      setTimeout(() => {
        const isError = document.getElementsByClassName('has-error')
        const input = isError[0].querySelector('input')
        //console.log(input)
        if (input !== null && input !== 'undefind' && input !== '') {
          isError[0].querySelector('input').focus()
            ? isError[0].querySelector('input').focus()
            : isError[0].querySelector('input').click()
        } else {
          isError[0].querySelector('textarea').focus()
        }
      }, 10)
      return false
    },

    sendPreviewDocByDocName(params) {
      this.previewLoading = true
      previewDocByDocName(this.applyid, params.materilaType, params.docfield).then(res => {
        this.previewLoading = false
        renderAsync(res, this.$refs.file, null, {
          className: 'text-docx', //class name/prefix for default and document style classes
          inWrapper: true, //enables rendering of wrapper around document content
          ignoreWidth: false, //disables rendering width of page
          ignoreHeight: false, //disables rendering height of page
          ignoreFonts: false, //disables fonts rendering
          breakPages: true, //enables page breaking on page breaks
          ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
          experimental: true, //enables experimental features (tab stops calculation)
          trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
          useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
          useMathMLPolyfill: true, //includes MathML polyfills for chrome, edge, etc.
          debug: false //enables additional logging
        }) // 渲染到页面
      })
    },
    // 下载材料
    download() {
      let params = this.initDocParams()
      this.previewLoading = true
      let materialName = Tp_procmaterialList.filter(element => element.value == params.materilaType)[0].name
      // 查找对应的文件名
      previewDocByDocName(this.applyid, params.materilaType, params.docfield)
        .then((res) => {
          const blob = new Blob([res],{type : "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
          var url = window.URL.createObjectURL(blob)
          var a = document.createElement('a')
          a.href = url
          a.download = materialName
          a.click()
        }).finally(() => {
          this.previewLoading = false
      })
    },
  }
}
